<!--
 * @Description: 
 * @Author: 胡涛
 * @Date: 2023-09-20 14:31:06
 * @LastEditors: 胡涛
 * @LastEditTime: 2023-11-11 11:41:38
-->
<template>
  <a-modal
    :keyboard="false"
    :maskClosable="false"
    :title="isEdit ? '修改' : '添加'"
    :width="800"
    :open="visible"
    @ok="onSubmit"
    @cancel="onClose"
    :confirmLoading="submitLoading"
  >
    <a-form
      ref="formRef"
      v-bind="formLayout"
      :rules="rules"
      :model="model"
      v-if="model"
    >
      <a-form-item has-feedback label="配置键名称" prop="key">
        <a-input v-model:value="model.key" :disabled="isEdit"></a-input>
      </a-form-item>
      <a-form-item has-feedback label="显示名称" prop="keyName">
        <a-input v-model:value="model.keyName"></a-input>
      </a-form-item>
      <a-form-item label="值类型" prop="keyType">
        <a-select
          :options="valueTypeOptions"
          v-model:value="model.keyType"
          placeholder="--请选择值类型--"
        >
        </a-select>
      </a-form-item>
      <a-form-item label="默认值">
        <a-textarea v-model="defaultValueString"></a-textarea>
      </a-form-item>
      <a-form-item label="组件类型" prop="controlType">
        <a-select
          v-model:value="model.controlType"
          :options="controlTypeOptions"
          placeholder="请选择组件"
          @change="onControlChanged"
        >
        </a-select>
      </a-form-item>
      <a-form-item label="组件属性" prop="controlProperty">
        <!-- <a-button size="small" type="primary" @click="propsVisible = true"
          >配置组件属性</a-button
        > -->
        <monaco-editor
          v-model:value="model.controlProperty"
          :rows="5"
          style="
            background-color: #333;
            font-size: 16px;
            line-height: 24px;
            color: #fff;
          "
        ></monaco-editor>
        <div style="padding: 10px; background: #f9f9f9">
          <component :is="controlType" v-bind="controlProperty" />
        </div>
      </a-form-item>
    </a-form>
    <!-- <config-props
      v-if="propsVisible"
      v-model="propsVisible"
      :item="controlProperty"
      @success="onControlPropsSuccess"
    ></config-props> -->
  </a-modal>
</template>
<script lang="ts" setup>
import { ConfigDefineDto } from "@/api/system/types";
import api from "@/api/system/configDefine";
// import ConfigProps from "./components/ConfigProps.vue";
import { computed, onMounted, ref } from "vue";
import { IOptionItem } from "@/types";
import { FormInstance, message } from "ant-design-vue";

type EditFieldProps = {
  visible: boolean;
  item?: any;
  id?: string;
  category: string;
  fields: Array<string>;
  action: "add" | "edit";
};

const props = withDefaults(defineProps<EditFieldProps>(), {
  action: "add",
  fields: () => {
    return [];
  },
  category: "",
});

const emits = defineEmits(["success", "change", "update:visible"]);

const model = ref<Partial<ConfigDefineDto>>({});
const controlTypeOptions: Array<IOptionItem> = [
  { label: "文本框", value: "a-input" },
  { label: "多行文本框", value: "a-textarea" },
  {
    label: "下拉框",
    value: "a-select",
    data: { options: [{ label: "<label>", value: "<value>" }] },
  },
  {
    label: "日期选择",
    value: "a-date-picker",
    data: { valueFormat: "YYYY-MM-DD", format: "YYYY-MM-DD" },
  },
  {
    label: "日期时间选择",
    value: "ADatePicker",
    data: {
      valueFormat: "YYYY-MM-DD HH:mm:ss",
      format: "YYYY-MM-DD HH:mm:ss",
      showTime: { format: "HH:mm:ss" },
    },
  },
  {
    label: "时间选择",
    value: "a-time-picker",
    data: { valueFormat: "HH:mm:ss", format: "HH:mm:ss" },
  },
  { label: "复选框", value: "a-checkbox" },
  { label: "单选组", value: "a-radio-group" }, 
  { label: "代码编辑器", value: "monaco-editor" }
];

const loading = ref(false);
const submitLoading = ref(false);

const valueTypeOptions: Array<IOptionItem> = [
  { label: "字符串", value: "string" },
  { label: "布尔", value: "bool" },
  { label: "数值", value: "number" },
  { label: "日期", value: "date" },
  { label: "JSON对象", value: "json" },
];
const defaultValueString = ref("");
const propsVisible = ref(false);

const controlType = computed(() => {
  return model.value.controlType || "a-input";
});

const controlProperty = computed(() => {
  let opts = controlTypeOptions.find(
    (x) => x.value === model.value.controlType
  );
  try {
    let args = JSON.parse(model.value.controlProperty || "{}");
    let defaultArgs = (opts || {}).data || {};
    return Object.assign({}, defaultArgs, args);
  } catch {
    return {};
  }
});

const rules = {
  category: [{ required: true, message: "请选择所属分类~" }],
  key: [{ required: true, message: "请输入配置键名称~" }],
  keyName: [{ required: true, message: "请输入配置项显示名称~" }],
};

const formLayout = {
  layout: "horizontal",
  labelCol: { span: 4 },
  wrapperCol: { span: 18 },
  labelAlign: "right",
};

const isEdit = computed(() => {
  return props.action == "edit";
});

onMounted(async () => {
  await loadData();
});
/**
 * 加载数据
 */
const loadData = async () => {
  if (!isEdit) {
    model.value = {
      category: props.category,
      key: "",
      keyType: "string",
      sortIndex: 0,
    };
    return;
  }
  if (props.id) {
    api.get(props.id).then((res: any) => {
      loading.value = false;
      model.value = res;
      parseDefaultString();
    });
  } else {
    if (props.item) {
      model.value = props.item;
      parseDefaultString();
      return;
    }
  }
  loading.value = true;
};

const parseDefaultString = () => {
  if (
    model.value.keyType === "string" &&
    model.value.defaultValue &&
    model.value.defaultValue !== ""
  ) {
    try {
      defaultValueString.value = JSON.parse(model.value.defaultValue);
    } catch (ex) {
      defaultValueString.value = model.value.defaultValue || "";
    }
  } else {
    defaultValueString.value = model.value.defaultValue || "";
  }
};

const onControlPropsSuccess = (props: any) => {
  model.value.controlProperty = JSON.stringify(props);
};

/**
 * 获取要提交默认值
 */

const defaultValueJson = computed(() => {
  if (defaultValueString.value && defaultValueString.value !== "") {
    return JSON.stringify(defaultValueString.value);
  } else {
    return "";
  }
});

/**
 *
 */
const onControlChanged = () => {
  let item = controlTypeOptions.find(
    (x) => x.value === model.value.controlType
  );
  if (item && item.data) {
    model.value.controlProperty = JSON.stringify(item.data, null, 4);
  } else {
    model.value.controlProperty = "{}";
  }
};

const formRef = ref();

/**
 * 提交保存
 */
const onSubmit = () => {
  let form = formRef.value as FormInstance;
  form.validate().then((value) => {
    if (!isEdit && props.fields.indexOf(model.value.key) !== -1) {
      message.error("字段名已存在，不允许重复添加");
      return;
    }
    model.value.defaultValue = defaultValueJson.value;
    emits("success", props.action, model.value);
    emits("update:visible", false);
  });
};

const onClose = () => {
  emits("update:visible", false);
};
</script>
